package com.zone.module_base.fragment

import android.util.Log
import com.liulishuo.okdownload.DownloadTask
import com.liulishuo.okdownload.SpeedCalculator
import com.liulishuo.okdownload.core.Util
import com.liulishuo.okdownload.core.breakpoint.BlockInfo
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo
import com.liulishuo.okdownload.core.cause.EndCause
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend
import com.zone.core.base.BaseBindingViewModelFragment
import com.zone.core.helper.DownloadHelper
import com.zone.module_base.BaseApp
import com.zone.module_base.databinding.FragmentTestDownloadBinding
import com.zone.module_base.viewmodel.TestFunctionViewModel

class TestDownloadFragment :
    BaseBindingViewModelFragment<FragmentTestDownloadBinding, TestFunctionViewModel>() {
    private val TAG = "TestDownloadFragment"
    val url =
        "https://z-cms-test.oss-cn-hangzhou.aliyuncs.com/content/file/2024-06-13/b5aa8ac7c3684dd7a58bc84902b06202.apk"
    lateinit var task: DownloadTask
    private var threadCount = 1

    override fun inject() {
        BaseApp.appComponent.inject(this)
    }

    override fun initDataBinding(binding: FragmentTestDownloadBinding) {
        super.initDataBinding(binding)

        binding.btStart.setOnClickListener {
            binding.etThreadCount.toString()
            threadCount = binding.etThreadCount.text.toString().toInt()
            startDownload(url)
        }
    }

    private fun startDownload(url: String): DownloadTask {
        return DownloadHelper.startDownload(
            url,
            threads = threadCount,
            listener = object : DownloadListener4WithSpeed() {
                private var totalLength: Long = 0
                private val readableTotalLength: String? = null

                override fun taskStart(p0: DownloadTask) {
                    Log.i(TAG, "【1、taskStart】");
                }

                override fun connectStart(
                    p0: DownloadTask,
                    p1: Int,
                    p2: MutableMap<String, MutableList<String>>
                ) {
                    Log.i(TAG, "【3、connectStart】 $p1");
                }

                override fun connectEnd(
                    p0: DownloadTask,
                    blockIndex: Int,
                    responseCode: Int,
                    p3: MutableMap<String, MutableList<String>>
                ) {
                    Log.i(TAG, "【4、connectEnd】$blockIndex ，$responseCode")
                }

                override fun taskEnd(
                    p0: DownloadTask,
                    cause: EndCause,
                    realCause: Exception?,
                    p3: SpeedCalculator
                ) {
                    if (cause == EndCause.PRE_ALLOCATE_FAILED) {
                        Log.i(TAG, "空间不足")
                    }
                    Log.i(
                        TAG,
                        ("【8、taskEnd】" + cause.name) + "：" + if (realCause != null) realCause.message else "无异常"
                    )
                }

                override fun infoReady(
                    p0: DownloadTask,
                    info: BreakpointInfo,
                    p2: Boolean,
                    p3: Listener4SpeedAssistExtend.Listener4SpeedModel
                ) {
                    totalLength = info.totalLength
                    Log.i(TAG, "【2、infoReady】总进度:${info.totalLength}")
                }

                override fun progressBlock(
                    p0: DownloadTask,
                    blockIndex: Int,
                    currentBlockOffset: Long,
                    p3: SpeedCalculator
                ) {
                    Log.i(TAG, "【5、progressBlock】$blockIndex，$currentBlockOffset");
                }

                override fun progress(
                    p0: DownloadTask,
                    currentOffset: Long,
                    taskSpeed: SpeedCalculator
                ) {
                    val readableOffset = Util.humanReadableBytes(currentOffset, true)
                    val progressStatus = "$readableOffset/$readableTotalLength"
                    val speed: String = taskSpeed.speed()
                    val percent = currentOffset.toFloat() / totalLength
                    Log.i(
                        TAG,
                        "【6、progress】$currentOffset[$progressStatus]，速度：$speed，进度：$percent%"
                    )
                    val formattedPercent = String.format("%.2f", percent)
                    viewModel.speed.set(speed)
                    viewModel.progress.set(formattedPercent.toFloat())
                    viewModel.fileSize.set(readableOffset)
                    viewModel.fileTotalLength.set(readableTotalLength)
                }

                override fun blockEnd(
                    p0: DownloadTask,
                    p1: Int,
                    p2: BlockInfo?,
                    p3: SpeedCalculator
                ) {

                }
            })
    }
}